import sys

from PyQt6.QtCharts import QChart, QChartView, QPieSeries
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPen
from PyQt6.QtWidgets import QApplication, QWidget


class MyChart(QWidget):
    def __init__(self):
        super(MyChart, self).__init__()
        self.setWindowTitle('饼图')

        # 图表视图
        chart = QChart()
        chart.setTitle('中国高等教育普及率')
        chart.legend().setAlignment(Qt.AlignmentFlag.AlignLeft)
        chartView = QChartView(self)
        chartView.setGeometry(10, 10, 800, 600)
        chartView.setChart(chart)

        # 设置数据
        data = {
            '儿童和老人': 35,
            '劳动人口': 49,
            '参加高考者': 7,
            '大学生': 8
        }
        series = QPieSeries()
        for item in data.items():
            series.append('%s (%d%%)' % item, item[1])
        series.setLabelsVisible(True)
        series.setHoleSize(0.2)
        series.setPieSize(0.6)

        # 设置第四条数据的状态
        slice = series.slices()[3]
        slice.setExploded(True)
        slice.setPen(QPen(Qt.GlobalColor.red, 2))
        slice.setBrush(Qt.GlobalColor.red)

        chart.addSeries(series)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MyChart()
    main.show()
    sys.exit(app.exec())
